package org.longs.converter;

import org.longs.stream.LittleAccessFile;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

public abstract class BaseConverter {
    private String filePath;
    private long total = 0;

    public void setTotal(long total) {
        this.total = total;
    }

    public long getTotal() {
        return total;
    }

    private long offset;

    public long getOffset() {
        return offset;
    }

    public void setOffset(long offset) {
        this.offset = offset;
    }

    private LittleAccessFile randomAccessFile;


    public LittleAccessFile getRandomAccessFile() {
        return randomAccessFile;
    }

    public abstract String getFlag();

    public BaseConverter(String filePath) {
        this.filePath = filePath;
    }


    public void close() throws IOException {
        this.randomAccessFile.close();
    }

    public BaseConverter(LittleAccessFile randomAccessFile) {
        this.randomAccessFile = randomAccessFile;
    }

    public String getFilePath() {
        return this.filePath;
    }

    public abstract void analysisBody(LittleAccessFile randomAccessFile) throws IOException;


    public void analysis() {
        try {
            if (this.filePath != null) {
                File file = new File(this.filePath);
                if (!file.exists()) {
                    throw new FileNotFoundException("找不到文件");
                }
                this.randomAccessFile = new LittleAccessFile(file, "r");
                if (this.randomAccessFile.length() < Integer.MAX_VALUE) {
                    setTotal((int) this.randomAccessFile.length());
                }
            } else {
                this.randomAccessFile.seek(getOffset());
            }
            String flag = getFlag();
            if (flag == null) {
                throw new RuntimeException("请填写标志位");
            }
            byte[] flagBytes = flag.getBytes(StandardCharsets.UTF_8);
            byte[] bytes = new byte[flagBytes.length];
            if (this.randomAccessFile.read(bytes) == -1) {
                return;
            }
            for (int i = 0; i < flagBytes.length; i++) {
                if (bytes[i] != flagBytes[i]) {
                    return;
                }
            }
            analysisBody(this.randomAccessFile);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
